<template>
	<view style="padding-bottom: 100rpx;">
		<custom-navbar :title="title"></custom-navbar>
		<!-- 		<view class="cards flex align between">
			<navigator url="/pages/manage/applyList" hover-class="none" class="card-nav flex align"
				style="border-right: solid 1rpx gainsboro;color: #428AF6;">
				<view>流动党员</view>
				<image mode="widthFix" src="/static/images/icon4.png"></image>
			</navigator>
			<navigator url="/pages/manage/suggestList" hover-class="none" class="card-nav flex align"
				style="color: #BC2D00;">
				<view>困难诉求</view>
				<image mode="widthFix" src="/static/images/icon5.png"></image>
			</navigator>
		</view> -->
		<view :style="'padding-top:'+barHeight+'px'"></view>
		<view class="cards" v-if="type==2">
			<view class="cards-tit">流入党员性别占比</view>
			<view class="charts-box">
				<qiun-data-charts :ontouch="true" type="ring" :opts="opts" :chartData="chartData" />
			</view>
		</view>
		<view class="cards" v-if="type==1">
			<view class="cards-tit">流出党员性别占比</view>
			<view class="charts-box">
				<qiun-data-charts :ontouch="true" type="ring" :opts="opts3" :chartData="chartData3" />
			</view>
		</view>
		<!-- 	<view class="cards flex align between">
			<navigator url="/pages/manage/applyList" hover-class="none" class="card-nav flex align"
				style="border-right: solid 1rpx gainsboro;color: #428AF6;font-size: 24rpx;">
				<view>流入党员流入党支部统计</view>
			</navigator>
			<navigator url="/pages/manage/suggestList" hover-class="none" class="card-nav flex align"
				style="color: #BC2D00;font-size: 24rpx;">
				<view>流入党员流入党支部统计</view>
			</navigator>
		</view> -->
		<view class="cards" v-if="type==2">
			<view class="cards-tit">流入党员行业占比（总人数：{{sumIn}}）</view>
			<view class="charts-box charts-box2">
				<qiun-data-charts type="pie" :opts="opts2" :chartData="chartData2" />
			</view>
		</view>
		<view class="cards" v-if="type==1">
			<view class="cards-tit">流出党员行业占比（总人数：{{sumOut}}）</view>
			<view class="charts-box charts-box2">
				<qiun-data-charts type="pie" :opts="opts2" :chartData="chartData4" />
			</view>
		</view>
		<view class="cards" v-if="type==1">
			<view class="cards-tit" style="margin-bottom: 20rpx;">流出党员流出党支部统计</view>
			<view class="uni-container">
				<uni-table border stripe emptyText="暂无更多数据">
					<!-- 表头行 -->
					<view class="tableHead">
						<uni-tr>
							<uni-th>
								<view style="width: 170rpx;">党支部</view>
							</uni-th>
							<uni-th>
								<view style="width: 170rpx;">流出人数</view>
							</uni-th>
							<uni-th align="left">
								<view style="width: 170rpx;">百分比</view>
							</uni-th>
						</uni-tr>
					</view>
					<!-- 表格数据行 -->
					<view class="tableBody">
						<uni-tr v-for="(item,index) in tableOut1" :key="index">
							<uni-td>
								<view style="width: 170rpx;">{{item.name}}</view>
							</uni-td>
							<uni-td>
								<view style="width: 170rpx;">{{item.value}}</view>
							</uni-td>
							<uni-td>
								<view style="width: 170rpx;">{{item.pers}}%</view>
							</uni-td>
						</uni-tr>
					</view>
				</uni-table>
			</view>
		</view>
		<view class="cards" v-if="type==2">
			<view class="cards-tit" style="margin-bottom: 20rpx;">流入党员流入党支部统计</view>
			<view class="uni-container">
				<uni-table border stripe emptyText="暂无更多数据">
					<!-- 表头行 -->
					<view class="tableHead">
						<uni-tr>
							<uni-th>
								<view style="width: 170rpx;">党支部</view>
							</uni-th>
							<uni-th>
								<view style="width: 170rpx;">流出人数</view>
							</uni-th>
							<uni-th>
								<view style="width: 170rpx;">百分比</view>
							</uni-th>
						</uni-tr>
					</view>
					<!-- 表格数据行 -->
					<view class="tableBody">
						<uni-tr v-for="(item,index) in tableIn1" :key="index">
							<uni-td>
								<view style="width: 170rpx;">{{item.name}}</view>
							</uni-td>
							<uni-td>
								<view style="width: 170rpx;">{{item.value}}</view>
							</uni-td>
							<uni-td>
								<view style="width: 170rpx;">{{item.pers}}%</view>
							</uni-td>
						</uni-tr>
					</view>
				</uni-table>
			</view>
		</view>
		<view class="cards" v-if="type==1">
			<view class="cards-tit" style="margin-bottom: 20rpx;">流出党员流入地统计</view>
			<view class="uni-container">
				<uni-table border stripe emptyText="暂无更多数据">
					<!-- 表头行 -->
					<view class="tableHead">
						<uni-tr>
							<uni-th>
								<view style="width: 170rpx;">地区</view>
							</uni-th>
							<uni-th>
								<view style="width: 170rpx;">流出人数</view>
							</uni-th>
							<uni-th>
								<view style="width: 170rpx;">百分比</view>
							</uni-th>
						</uni-tr>
					</view>
					<!-- 表格数据行 -->
					<view class="tableBody">
						<uni-tr v-for="(item,index) in tableOut2" :key="index">
							<uni-td>
								<view style="width: 170rpx;">{{item.name}}</view>
							</uni-td>
							<uni-td>
								<view style="width: 170rpx;">{{item.value}}</view>
							</uni-td>
							<uni-td>
								<view style="width: 170rpx;">{{item.pers}}%</view>
							</uni-td>
						</uni-tr>
					</view>
				</uni-table>
			</view>
		</view>
		<view class="cards" v-if="type==2">
			<view class="cards-tit" style="margin-bottom: 20rpx;">流入党员流出地统计</view>
			<view class="uni-container">
				<uni-table border stripe emptyText="暂无更多数据">
					<!-- 表头行 -->
					<view class="tableHead">
						<uni-tr>
							<uni-th>
								<view style="width: 170rpx;">地区</view>
							</uni-th>
							<uni-th>
								<view style="width: 170rpx;">流出人数</view>
							</uni-th>
							<uni-th>
								<view style="width: 170rpx;">百分比</view>
							</uni-th>
						</uni-tr>
					</view>
					<!-- 表格数据行 -->
					<view class="tableBody">
						<uni-tr v-for="(item,index) in tableIn2" :key="index">
							<uni-td>
								<view style="width: 170rpx;">{{item.name}}</view>
							</uni-td>
							<uni-td>
								<view style="width: 170rpx;">{{item.value}}</view>
							</uni-td>
							<uni-td>
								<view style="width: 170rpx;">{{item.pers}}%</view>
							</uni-td>
						</uni-tr>
					</view>
				</uni-table>
			</view>
		</view>
	</view>
</template>

<script>
	import CustomNavbar from '@/components/custom-navbar.vue';
	import {
		userSexData,
		userJobData,
		adminWxbind,
		adminDetail,
		adminWxunbind,
		industryData,
		organizationData,
		regionData
	} from '@/api/apiData.js';
	export default {
		data() {
			return {
				title: '',
				statusBarHeight: 20,
				barHeight: 44,
				barWidth: null,
				wxapp_openid: '',
				chartData: {},
				chartData2: {},
				chartData3: {},
				chartData4: {},
				type: 1,
				opts: {
					rotate: false,
					rotateLock: false,
					color: ["#F37A33", "#4E82EE"],
					fontSize: 12,
					padding: [5, 5, 5, 5],
					dataLabel: true,
					enableScroll: false,
					legend: {
						show: true,
						position: "bottom",
						lineHeight: 25
					},
					title: {
						name: "总人数",
						fontSize: 12,
						color: "#666666"
					},
					subtitle: {
						name: "1060",
						fontSize: 18,
						color: "#C23015"
					},
					extra: {
						ring: {
							ringWidth: 20,
							activeOpacity: 0.5,
							activeRadius: 10,
							offsetAngle: 0,
							labelWidth: 15,
							border: true,
							borderWidth: 1,
							borderColor: "#FFFFFF"
						}
					}
				},
				opts2: {
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc", "#aa5500", "#ce0aff", "#ff401a", "#468faa", "#46ffe1", "#fffbb5", "#c0f5ff"
					],
					padding: [5, 5, 5, 5],
					enableScroll: false,
					legend: { // 图例配置
						show: true, // 显示图例
						position: 'bottom', // 图例位置，如'right', 'left', 'top', 'bottom'等
						formatter: '{name}：{value}个', // 图例文本格式化，{name}为名称，{value}为值
						padding: 20, // 图例内边距
						lineHeight: 20, // 图例间隔
						float: 'left',
						textStyle: { // 图例文字样式
							color: '#666666', // 文字颜色
							fontSize: 10, // 文字大小
						},
					},
					extra: {
						pie: {
							activeOpacity: 0.5,
							activeRadius: 10,
							offsetAngle: 0,
							labelWidth: 15,
							border: false,
							borderWidth: 3,
							borderColor: "#FFFFFF"
						}
					}
				},
				opts3: {
					rotate: false,
					rotateLock: false,
					color: ["#F37A33", "#4E82EE"],
					fontSize: 12,
					padding: [5, 5, 5, 5],
					dataLabel: true,
					enableScroll: false,
					legend: {
						show: true,
						position: "bottom",
						lineHeight: 25
					},
					title: {
						name: "总人数",
						fontSize: 12,
						color: "#666666"
					},
					subtitle: {
						name: "1060",
						fontSize: 18,
						color: "#C23015"
					},
					extra: {
						ring: {
							ringWidth: 20,
							activeOpacity: 0.5,
							activeRadius: 10,
							offsetAngle: 0,
							labelWidth: 15,
							border: true,
							borderWidth: 1,
							borderColor: "#FFFFFF"
						}
					}
				},
				sumIn: '',
				sumOut: '',
				barHeight: '',
				tableOut1: [],
				tableOut2: [],
				tableIn1: [],
				tableIn2: [],
			};
		},
		components: {
			CustomNavbar
		},
		onLoad(option) {
			this.type = option.type
			if (option.type == 1) {
				this.title = '流出党员数据统计'
			} else {
				this.title = '流入党员数据统计'
			}
		},
		created() {
			const systemInfo = uni.getSystemInfoSync();
			let statusBarHeight = systemInfo.statusBarHeight; // 获取状态栏高度
			let navBarHeight = ''
			if (systemInfo.platform === 'android') {
				navBarHeight = statusBarHeight + 48; // Android 导航栏高度
			} else {
				navBarHeight = statusBarHeight + 44; // iOS 导航栏高度
			}
			this.barHeight = navBarHeight
		},
		onShow() {
			let token = uni.getStorageSync('token2')
			if (token) {
				uni.request({
					url: 'https://xsdy.ncscloudmedia.com/ymadmin.php/admin/checkToken',
					data: {},
					method: 'POST',
					header: {
						'content-type': 'application/json',
						'token': token
					},
					success: result => {
						if (result.data.code == 1) {
							this.getDetail()
							this.getServerData()
							this.getServerData2()
							this.getTable()
						} else {
							uni.reLaunch({
								url: '/pages/login/loginM'
							})
						}
					},
					fail: result => {
						uni.hideLoading();
					}
				})
			} else {
				uni.reLaunch({
					url: '/pages/login/loginM'
				})
			}
		},
		methods: {
			toBack() {
				uni.navigateBack()
			},
			// 获取用户详情
			async getDetail() {
				const result = await adminDetail()
				if (result.code == 1) {
					if (result.data.wxapp_openid != null) {
						this.wxapp_openid = result.data.wxapp_openid
					}
				}
			},
			async getTable() {
				const result1 = await organizationData()
				if (result1.code == 1) {
					const sumIn1 = result1.data.in.reduce((accumulator, currentValue) => {
						return accumulator + currentValue.value;
					}, 0);
					const sumOut1 = result1.data.out.reduce((accumulator, currentValue) => {
						return accumulator + currentValue.value;
					}, 0);
					result1.data.in.forEach(item=>{
						item.pers = ((Number(item.value)/Number(sumIn1))*100).toFixed(2)
					})
					result1.data.out.forEach(item=>{
						item.pers = ((Number(item.value)/Number(sumOut1))*100).toFixed(2)
					})
					result1.data.in.sort((a, b) => b.value - a.value);
					result1.data.out.sort((a, b) => b.value - a.value);
					this.tableIn1 = result1.data.in
					this.tableOut1 = result1.data.out
				
				}
				const result2 = await regionData()
				if (result2.code == 1) {
					const sumIn1_s = result2.data.in.reduce((accumulator, currentValue) => {
						return accumulator + currentValue.value;
					}, 0);
					const sumOut1_s = result2.data.out.reduce((accumulator, currentValue) => {
						return accumulator + currentValue.value;
					}, 0);
					result2.data.in.forEach(item=>{
						item.pers = ((Number(item.value)/Number(sumIn1_s))*100).toFixed(2)
					})
					result2.data.out.forEach(item=>{
						item.pers = ((Number(item.value)/Number(sumOut1_s))*100).toFixed(2)
					})
					result2.data.in.sort((a, b) => b.value - a.value);
					result2.data.out.sort((a, b) => b.value - a.value);
					this.tableIn2 = result2.data.in
					this.tableOut2 = result2.data.out
				}
			},
			// 订阅消息
			toBook() {
				if (this.wxapp_openid == '') {
					uni.showModal({
						title: '提示',
						content: '请先绑定微信',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								// console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				} else {
					let that = this
					wx.getSetting({
						withSubscriptions: true,
						success(res) {
							let templateId = "eAvm1oL34Z7_IVf4D7jblQsaWvXYCfR8lIKe31nft-0"; //替换为你的模板ID
							let subscriptionStatus = res.subscriptionsSetting[templateId];
							if (subscriptionStatus === "accept") {
								//用户已订阅
								console.log("用户已订阅");
								uni.showToast({
									title:'您已订阅该消息',
									icon:'none'
								})
								// uni.showModal({
								// 	title: '提示',
								// 	content: '您已订阅该消息',
								// 	showCancel: false,
								// 	success: function(res) {
								// 		if (res.confirm) {
								// 			// console.log('用户点击确定');
								// 		} else if (res.cancel) {
								// 			console.log('用户点击取消');
								// 		}
								// 	}
								// });
							} else if (subscriptionStatus === "reject") {
								//用户拒绝订阅
								console.log("用户拒绝订阅");
								uni.showToast({
									title: "你已拒绝订阅",
									icon: "error",
								});
								that.toBookCom()
							} else if (subscriptionStatus === "ban") {
								//订阅消息被封禁
								console.log("订阅消息被封禁");
								uni.showToast({
									title: "订阅消息被封禁",
									icon: "error",
								});
								that.toBookCom()
							} else {
								//用户未订阅或未授权
								console.log("用户未订阅或未授权");
								that.toBookCom()
							}

						}

					});
				}
			},
			toBookCom() {
				let id = "eAvm1oL34Z7_IVf4D7jblQsaWvXYCfR8lIKe31nft-0"; // 替换你自己的模板ID 模板详情那里就有模板ID
				// 调用订阅消息API
				let that = this
				uni.requestSubscribeMessage({
					tmplIds: [id], // 这里填写你的模板ID数组
					success(res) {
						if (res[id] === 'accept') {
							// 用户同意订阅该模板
							uni.showToast({
								title: "订阅成功",
								icon: "success",
							});
						}
						if (res[id] === 'reject') {
							// 用户拒绝订阅该模板
							uni.showModal({
								title: "订阅失败",
								content: "您已设置不再询问，请前往设置开启订阅提醒。",
								confirmText: "去设置",
								success(modalRes) {
									if (modalRes.confirm) {
										that.openSetting();
									} else {
										uni.showToast({
											title: "您可能错过重要通知",
											icon: "none",
										});
									}
								},
							});
						}
					},
					fail(err) {
						console.error('订阅消息失败', err);
					}
				});

			},
			openSetting() {
				uni.openSetting({
					success(res) {
						console.log("设置界面返回：", res);
						if (res.subscriptionsSetting) {
							console.log("订阅消息授权状态：", res.subscriptionsSetting);
						}
					},
					fail(err) {
						console.error("打开设置失败：", err);
					},
				});
			},
			// 绑定微信
			toBind() {
				let that = this
				if (that.wxapp_openid == '') {
					uni.login({
						provider: 'weixin', //使用微信登录
						success(lres) {
							console.log(lres, '获取到的code--------1');
							let code = lres.code
							that.wxbind(code)
						}
					})
				} else {
					uni.showModal({
						title: '提示',
						content: '确定要解绑微信吗？',
						success: function(res) {
							if (res.confirm) {
								that.wxunbind()
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}

			},
			async wxbind(code) {
				const result = await adminWxbind({
					code: code
				})
				if (result.code == 1) {
					uni.showToast({
						title: result.msg
					})
					setTimeout(() => {
						this.getDetail()
					}, 1000)
				} else {
					uni.showToast({
						title: result.msg,
						icon: 'error'
					})
				}
			},
			async wxunbind() {
				const result = await adminWxunbind()
				if (result.code == 1) {
					uni.showToast({
						title: result.msg
					})
					setTimeout(() => {
						this.getDetail()
					}, 1000)
				} else {
					uni.showToast({
						title: result.msg,
						icon: 'error'
					})
				}
			},
			async getServerData() {
				const result = await userSexData()
				let datas = result.data
				//模拟从服务器获取数据时的延时
				let sum = Number(datas.in[1]) + Number(datas.in[2])
				let per1 = ((Number(datas.in[1]) / sum) * 100).toFixed(2)
				let per2 = ((Number(datas.in[2]) / sum) * 100).toFixed(2)
				let res = {
					series: [{
						data: [{
							"name": "男性",
							"value": datas.in[1],
							"labelText": "男性:" + datas.in[1] + "(" + per1 + "%)"
						}, {
							"name": "女性",
							"value": datas.in[2],
							"labelText": "女性:" + datas.in[2] + "(" + per2 + "%)"
						}]
					}],

				};
				let sum2 = Number(datas.out[1]) + Number(datas.out[2])
				let perout1 = ((Number(datas.out[1]) / sum2) * 100).toFixed(2)
				let perout2 = ((Number(datas.out[2]) / sum2) * 100).toFixed(2)
				let res2 = {
					series: [{
						data: [{
							"name": "男性",
							"value": datas.out[1],
							"labelText": "男性:" + datas.out[1] + "(" + perout1 + "%)"
						}, {
							"name": "女性",
							"value": datas.out[2],
							"labelText": "女性:" + datas.out[2] + "(" + perout2 + "%)"
						}]
					}]
				};
				this.chartData = JSON.parse(JSON.stringify(res));
				this.chartData3 = JSON.parse(JSON.stringify(res2));
				let nums = Number(datas.in[0]) + Number(datas.in[1]) + Number(datas.in[2])
				let nums2 = Number(datas.out[0]) + Number(datas.out[1]) + Number(datas.out[2])
				this.opts.subtitle.name = nums
				this.opts3.subtitle.name = nums2
			},
			async getServerData2() {
				const result = await industryData()
				let datas = result.data
				let dataIn = result.data.in
				let dataOut = result.data.out
				const sum = dataIn.reduce((accumulator, currentValue) => {
					return accumulator + currentValue.value;
				}, 0);
				const sum2 = dataOut.reduce((accumulator, currentValue) => {
					return accumulator + currentValue.value;
				}, 0);
				console.log(sum); // 输出：60
				this.sumIn = sum
				this.sumOut = sum2
				// dataIn.forEach(item=>{
				// 	item.labelText = item.name+':'+item.value
				// })
				let res = {
					series: [{
						data: dataIn
					}]
				};
				let res2 = {
					series: [{
						data: dataOut
					}]
				};
				this.chartData2 = JSON.parse(JSON.stringify(res));
				this.chartData4 = JSON.parse(JSON.stringify(res2));
			},
			addNewLines(str, charsPerLine) {
				return str.replace(new RegExp(`(.{1,${charsPerLine}})`, 'g'), '$1\n');
			}
		}
	}
</script>

<style lang="scss" scoped>
	.nabbar {
		background: #FF9008;
	}

	.uni-container {
		height: 600rpx;
		position: relative;
	}

	/* //表头固定样式 */
	::v-deep .tableHead {
		font-weight: bold;
		color: #333333;
		background: #F4F6FF;
		z-index: 20;
		position: absolute;
		top: 0rpx;
	}

	::v-deep .tableBody {
		height: 500rpx;
		overflow-y: scroll;
		overflow-x: hidden;
		margin-top: 44px;
		background-color: #fff;
	}

	.bookBtn {
		position: fixed;
		top: 400rpx;
		right: 0;
		background: #55aaff;
		color: white;
		padding: 10rpx 20rpx;
		border-radius: 8rpx 0 0 8rpx;
		font-size: 28rpx;
		width: 20rpx;
	}

	.bookBtn2 {
		top: 150rpx;
		background: #55aa7f;
	}

	.cards {
		margin: 35rpx 32rpx;
		background: white;
		box-shadow: 1rpx 2rpx 1rpx 1rpx gainsboro;
		border-radius: 8rpx;
		padding: 16rpx 24rpx;

		.cards-tit {
			font-size: 28rpx;
		}

		.card-nav {
			flex: 1;
			text-align: center;
			justify-content: center;
			padding: 20rpx 0;
			font-size: 28rpx;

			image {
				width: 43rpx;
				height: 46rpx;
				margin-left: 20rpx;
			}
		}
	}

	.charts-box {
		width: 100%;
		height: 380rpx;
	}

	.charts-box2 {
		height: 800rpx;
	}
</style>